#Guessing game
import random #Necessary for generating random numbers.

guess = None #Create a global variable named guess so that both functions
             # can use it.

def tryGuess():
    global guess #Declare guess as the global variable named guess, not a local.
    guess = None #Set it to None so the while loop will work.

    #Prompt the user for an integer between 1-100. If anything else, catch the
    # exception.
    while not guess:
        try:
            guess = int(raw_input("Pick a number between 1 and 100: "))
        except ValueError:
            print "Invalid integer!"
                
def guessGame():
    global guess #Declare guess as the global variable.
    print "Time to play a guessing game." #Let the user know the game has started.

    number = random.randint(1,100) #Randomly pick a number 1-100.

    tryGuess() #Call tryGuess() to prompt the user for a guess.

    tries = 1 #This is the user's first try.

    #As long as the user's guess is incorrect, continue this loop and tell the
    # user if he/she is too high or too low. Call tryGuess() again for another
    # guess.
    while guess != number:
        tries = tries + 1
        if guess > number:
            print "Too high, guess again!"
            tryGuess()
        elif guess < number:
            print "Too low, guess again!"
            tryGuess()
    #If the user guesses correctly, tell them how many tries it took them and
    # end the game.
    if guess == number:
        print "Congratulations! You guessed the number after", tries, "attempts!"

guessGame() #Call guessGame() to start the game!
